package link.cocoon.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import link.cocoon.blog.entity.Article;
import link.cocoon.blog.service.ArticleService;
import link.cocoon.blog.service.CategoryService;
import link.cocoon.common.base.BaseController;
import link.cocoon.common.resp.RespData;
import link.cocoon.system.entity.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Cocoon
 * @since 2020-03-31
 */
@RestController
@RequestMapping( "/blog/article" )
public class ArticleController extends BaseController<Article, ArticleService> {

  @Resource
  private CategoryService categoryService;

  @Override
  public RespData<Integer> create(@RequestBody @Valid Article model) {
    User user = getCurrentUser();
    if (user == null) {
      return RespData.error("请重新登陆后尝试");
    }
    model.setCreateBy(user.getId());
    return super.create(model);
  }

  @Override
  protected LambdaQueryWrapper<Article> getWrapper(Map<String, String> params) {
    LambdaQueryWrapper<Article> wrapper = super.getWrapper(params);
    if (params.get("categoryId") != null) {
      Long categoryId = Long.valueOf(params.get("categoryId"));
      List<Long> categoryIdList = categoryService.findAllChildrenIdById(categoryId);
      wrapper.in(Article::getCategoryId, categoryIdList);
    }
    return wrapper;
  }


}
